//
//  HJAppointmentsDetailController.m
//  Keping
//
//  Created by a on 2017/8/30.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HJAppointmentsDetailController.h"
#import "HJAppointmentsDetailCell.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import <ShareSDKUI/SSUIShareActionSheetItem.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>
#import "HJAppointmentRequest.h"
#import "GPIMController.h"

@interface HJAppointmentsDetailController ()<UITableViewDelegate,UITableViewDataSource>
/**
 tableView
 */
@property(nonatomic,weak)UITableView*tableView;
/**
 数据源
 */
@property(nonatomic,strong)NSArray *dataAry;

@property (nonatomic, strong) id AppointmentDetailModel;
@end

@implementation HJAppointmentsDetailController

-(NSArray *)dataAry
{
    if (!_dataAry) {
        _dataAry=@[@"Full Name",@"Mobile phone Number",@"Email Address",@"Vehicle Plate Number",@"Time",@"Validity"];
    }
    return _dataAry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
    [self setUI];
}

- (void)getData {
    [super getData];
    [self showLoading];
    WEAKSELF
    if ([self.AppointmentModel isKindOfClass:[VisitEntityViews class]]) {//拜访详情
        VisitEntityViews *entity = self.AppointmentModel;
        HJAppoInvitevisitEntitysDetailRequest *request = [[HJAppoInvitevisitEntitysDetailRequest alloc] initWithVisitEntitysID:entity.id];
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            NSDictionary *dict = request.responseObject;
            NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
            if (status == 200) {
                VisitEntityViews *model= [VisitEntityViews modelWithDictionary:[dict objectForKey:@"visitEntityView"]];
                weakSelf.AppointmentDetailModel = model;
                [weakSelf.tableView reloadData];
            } else {
                [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            [weakSelf showError:request.error];
        }];
    } else {
        HJAppointmentModel *entity = self.AppointmentModel;//邀请详情
        HJAppoinviteInviteEntityItemsDetailRequest *request = [[HJAppoinviteInviteEntityItemsDetailRequest alloc] initWithInviteEntityItemsID:entity.id];
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            NSDictionary *dict = request.responseObject;
            NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
            if (status == 200) {
                HJAppointmentModel *model = [HJAppointmentModel modelWithDictionary:[dict objectForKey:@"inviteEntityItemView"]];
                self.AppointmentDetailModel = model;
                [weakSelf.tableView reloadData];
            } else {
                [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            [weakSelf showError:request.error];
        }];
    }
}

-(void)setUI
{
    self.navigationItem.title=@"Details";
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    [btn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 20, 20);
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [btn addTarget:self action:@selector(actionForShare) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    UITableView*tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor colorWithHexString:@"#f2f1f6"];
    [self.view addSubview:tableView];
    self.tableView=tableView;
}

- (void)actionForShare {
    NSString *shareText;
    NSString *title;
    if ([self.AppointmentDetailModel isKindOfClass:[VisitEntityViews class]]) {
        //邀请详情
        VisitEntityViews *entity = self.AppointmentDetailModel;
        shareText = [NSString stringWithFormat:@"http://39.108.84.209/intelligentcommunity/wap/access/visitentitys/%@.htm",entity.id];
        title = @"My Visits";
        

        
    } else {
        //拜访详情
        HJAppointmentModel *model = self.AppointmentDetailModel;
        shareText = [NSString stringWithFormat:@"http://39.108.84.209/intelligentcommunity/wap/access/inviteentityitems/%@.htm",model.id];
        title = @"My Guests";

    }
    WEAKSELF
    SSUIShareActionSheetItem *item = [SSUIShareActionSheetItem itemWithIcon:[UIImage imageNamed:@"ic_friend"] label:@"Friends" onClick:^{
        GPIMController *vc = [[GPIMController alloc] initWithIndex:1 isShare:YES shareText:shareText];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSArray *array = @[@(SSDKPlatformTypeSMS),item,@(SSDKPlatformTypeWhatsApp)];
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:shareText
                                     images:nil
                                        url:[NSURL URLWithString:@"https://www.linktime.com.my/"]
                                      title:title
                                       type:SSDKContentTypeText];
    //有的平台要客户端分享需要加此方法，例如微博
    [shareParams SSDKEnableUseClientShare];
    //2、分享（可以弹出我们的分享菜单和编辑界面）
    [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                             items:array
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                       case SSDKResponseStateBegin:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kBlueColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kBlueColor}];
                           //设置UI等操作
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Share Success!"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Share Fail!"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Share Cancel!"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           break;
                       }
                           break;
                       default:
                           break;
                   }
               }
     ];
}

- (NSString *)getValidityDate:(NSTimeInterval )date {
    NSTimeInterval time = date / 1000.0;
    NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:locale]; //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm a"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    KLog(@"时间戳转化时间 >>> %@",currentDateStr);
    return currentDateStr;
}


#pragma mark --UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    HJAppointmentsDetailCell*cell=[HJAppointmentsDetailCell cellWithTableView:tableView];
    cell.title=self.dataAry[indexPath.row];
    if ([self.AppointmentDetailModel isKindOfClass:[VisitEntityViews class]]) {
        VisitEntityViews *entity = self.AppointmentDetailModel;
        switch (row) {
            case 0:
                cell.content = entity.fullName;
                break;
            case 1:
                cell.content = entity.phone;
                break;
            case 2:
                cell.content = entity.email;
                break;
            case 3:
                cell.content = entity.vehicleNumber;
                break;
            case 4:
                cell.content = [self getValidityDate:entity.visitTime];
                break;
            case 5:
                cell.content = entity.validityTime;
                break;
            default:
                break;
        }
    } else {
        HJAppointmentModel *model = self.AppointmentDetailModel;
        switch (row) {
            case 0:
                cell.content = model.fullName;
                break;
            case 1:
                cell.content = model.phone;
                break;
            case 2:
                cell.content = model.email;
                break;
            case 3:
                cell.content = model.vehicleNumber;
                break;
            case 4:
                cell.content = [self getValidityDate:[model.visitTime doubleValue]];
                break;
            case 5:
                cell.content = model.validityTime;
                break;
            default:
                break;
        }
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(50);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([self.AppointmentDetailModel isKindOfClass:[HJAppointmentModel class]]) {
        HJAppointmentModel *model = self.AppointmentDetailModel;
        CGFloat heigth = [self heightForString:model.message andWidth:self.view.width - 20];
        if ([model.type isEqualToString:@"visit"] && [model.status isEqualToString:@"Upcoming"]) {
            return K_FactorH(230/2) + 148.0 + heigth + 10;
        }
    }
    VisitEntityViews *entity = self.AppointmentModel;
    CGFloat heigth = [self heightForString:entity.message andWidth:self.view.width - 20];
    if ([entity.status isEqualToString:@"create"]) {
        return K_FactorH(230/2) + 148.0 + heigth + 10;
    }
    return K_FactorH(230/2) + heigth +  10;
}

//计算高度
- (float) heightForString:(NSString *)value andWidth:(float)width{
    CGSize frame = [value boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                      options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin
                                   attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}
                                      context:nil].size;
    return frame.height;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView*footerView=[[UIView alloc]init];
    footerView.backgroundColor=[UIColor whiteColor];

    if ([self.AppointmentDetailModel isKindOfClass:[VisitEntityViews class]]) {
        VisitEntityViews *entity = self.AppointmentModel;
        CGFloat heigth = [self heightForString:entity.message andWidth:self.view.width];
        
        UILabel *message = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, self.view.width - 20, heigth)];
        message.text = entity.message;
        message.numberOfLines = 0;
        message.font = [UIFont systemFontOfSize:14];
        [footerView addSubview:message];
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, message.height + 10 , K_FactorH(230/2),  K_FactorH(230/2))];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(K_FactorH(230/2) + 10, message.height + 10, self.view.width - (K_FactorH(230/2) + 10),  K_FactorH(230/2))];
        label.text = @"Please show the invitation card to the person on duty at the guard house.\nPlease note that you still have to go through the visitor registration process.";
        label.font = [UIFont systemFontOfSize:12];
        label.numberOfLines = 0;
        
        if (StringNotNull(entity.qrCode)) {
            [imageview sd_setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingPathComponent:entity.qrCode]] placeholderImage:nil];
        }
        
//        if ([entity.status isEqualToString:@"create"]) {
//            UIButton *tybtn = [UIButton commonButtonWithTitle:@"Accept"];
//            tybtn.layer.cornerRadius = 20.0;
//            [tybtn setFrame:CGRectMake(20, label.y + label.height + 15, kScreenWidth - 40, 44.0)];
//            [tybtn addTarget:self action:@selector(actionForTongYi:) forControlEvents:UIControlEventTouchUpInside];
//            [footerView addSubview:tybtn];
//
//            UIButton *rejectbtn = [UIButton buttonWithType:UIButtonTypeCustom];
//            [rejectbtn setTitle:@"Reject" forState:UIControlStateNormal];
//            [rejectbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//            [rejectbtn setFrame:CGRectMake(20, tybtn.y + tybtn.height + 15, kScreenWidth - 40, 44.0)];
//            rejectbtn.layer.masksToBounds= YES;
//            rejectbtn.layer.cornerRadius = 20.0;
//            [rejectbtn.layer setBorderWidth:1.0];
//            rejectbtn.hidden = YES;
//            [rejectbtn.layer setBorderColor:[UIColor grayColor].CGColor];
//            [rejectbtn addTarget:self action:@selector(actionForReject:) forControlEvents:UIControlEventTouchUpInside];
//            [footerView addSubview:rejectbtn];
//        }
        
        label.textColor=[UIColor colorWithHexString:@"#4c4c4c"];
        [footerView addSubview:label];
        [footerView addSubview:imageview];
        
    } else {
        HJAppointmentModel *model = self.AppointmentDetailModel;
        CGFloat heigth = [self heightForString:model.message andWidth:self.view.width];
        UILabel *message = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, self.view.width - 20, heigth)];
        message.text = model.message;
        message.numberOfLines = 0;
        message.font = [UIFont systemFontOfSize:14];
        [footerView addSubview:message];
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, message.height + 10, K_FactorH(230/2),  K_FactorH(230/2))];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(K_FactorH(230/2) + 10, message.height + 10, self.view.width - (K_FactorH(230/2) + 10),  K_FactorH(230/2))];
        label.text = @"Please show the invitation card to the person on duty at the guard house.\nPlease note that you still have to go through the visitor registration process.";
        label.font = [UIFont systemFontOfSize:12];
        label.numberOfLines = 0;
        if (StringNotNull(model.qrCode)) {
            [imageview sd_setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingPathComponent:model.qrCode]] placeholderImage:nil];
        }
        if ([model.type isEqualToString:@"visit"] && [model.status isEqualToString:@"Upcoming"]) {
            UIButton *tybtn = [UIButton commonButtonWithTitle:@"Accept"];
            tybtn.layer.cornerRadius = 20.0;
            [tybtn setFrame:CGRectMake(20, label.y + label.height + 15, kScreenWidth - 40, 44.0)];
            [tybtn addTarget:self action:@selector(actionForTongYi:) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:tybtn];
            
            UIButton *rejectbtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [rejectbtn setTitle:@"Reject" forState:UIControlStateNormal];
            [rejectbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [rejectbtn setFrame:CGRectMake(20, tybtn.y + tybtn.height + 15, kScreenWidth - 40, 44.0)];
            rejectbtn.layer.masksToBounds= YES;
            rejectbtn.layer.cornerRadius = 20.0;
            [rejectbtn.layer setBorderWidth:1.0];
            rejectbtn.hidden = YES;
            [rejectbtn.layer setBorderColor:[UIColor grayColor].CGColor];
            [rejectbtn addTarget:self action:@selector(actionForReject:) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:rejectbtn];
        }
        
        label.textColor=[UIColor colorWithHexString:@"#4c4c4c"];
        [footerView addSubview:label];
        [footerView addSubview:imageview];
    }
    return footerView;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView*headerView=[[UIView alloc]init];
    headerView.backgroundColor=[UIColor clearColor];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.width,  K_FactorH(40))];
    id obj = self.AppointmentDetailModel;
    if ([obj isKindOfClass:[VisitEntityViews class]]) {
        VisitEntityViews *entity = obj;
        label.text= [NSString stringWithFormat:@"status: %@",entity.statusStr];
    } else {
        HJAppointmentModel *model = obj;
        label.text= [NSString stringWithFormat:@"status: %@",model.statusStr];
    }
    label.textColor=[UIColor colorWithHexString:@"#666668"];
    label.textAlignment=NSTextAlignmentCenter;
    [headerView addSubview:label];
    return headerView;
}

- (void)actionForTongYi:(UIButton *)button {
    [self uploadAppoInviteGuestForReject:NO];
}

- (void)actionForReject:(UIButton *)buttton {
    [self uploadAppoInviteGuestForReject:YES];
}

- (void)uploadAppoInviteGuestForReject:(BOOL )isReject {
    NSString *model_id;
    if ([self.AppointmentDetailModel isKindOfClass:[HJAppointmentModel class]]) {
        HJAppointmentModel *appointment = self.AppointmentDetailModel;
        model_id = appointment.id;
    } else {
        VisitEntityViews *entity = self.AppointmentModel;
        model_id = entity.id;
    }
    HJAppoInviteGuestRequest *request = [[HJAppoInviteGuestRequest alloc] initWithGuestID:model_id];
    request.params = @{@"status":isReject ? @"reject" : @"ing"};
    WEAKSELF
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            if (weakSelf.indexPath) {
                [weakSelf showSuccess:[dict objectForKey:@"msg"]];
            }
            
            if ([weakSelf.AppointmentDetailModel isKindOfClass:[HJAppointmentModel class]]) {
                HJAppointmentModel *appointment = self.AppointmentDetailModel;
                appointment.status = isReject ? @"reject" : @"ing";
                appointment.statusStr = @"Upcoming";
                weakSelf.uploadDataSource(weakSelf.indexPath);
            } else {
                VisitEntityViews *entity = self.AppointmentModel;
                entity.status = isReject ? @"reject" : @"ing";
                entity.statusStr = @"Upcoming";
                weakSelf.uploadDataSource(weakSelf.indexPath);
            }
            [weakSelf getData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
